package com.xtxb.utils.log.impl.file;

import com.xtxb.utils.log.config.LoggerConf;

import java.io.*;

/**
 * 作者: xtxb-fedora
 * <p>
 * 日期: 2021年01月22日-下午5:43
 * <p>
 * 版权说明：xtxb
 * <p>
 *
 */
public class FileOut  implements Runnable{
    private long timestamp=0;
    private BufferedWriter writer=null;

    public FileOut(){
        Thread t=new Thread(new ThreadGroup("debug_log"),this,"Debug Log Out Thread");
        t.setDaemon(true);
        t.start();
    }

    protected  BufferedWriter getOut(){
        if(writer==null){
            try {
                writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(LoggerConf.getLogPath(),true)));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        timestamp=System.currentTimeMillis();
        return writer;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (true){
            if(writer!=null && System.currentTimeMillis()-timestamp>10*1000 ){
                synchronized (writer){
                    try {
                        writer.flush();
                        writer.close();
                        System.out.println("Log file closed");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    writer=null;
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}